
#include "wifis.h"
#include "mqtts.h"
#include "main.h"
#include "assitant.h"
String ssid = "CMCC-7cFE";
String password = "********";
#define __known_ssids_list_len 8
String wlans[8][2] = {{"HUAWEI-M6", "huawei-m6"}, {"CMCC-dVKe", "********"}};
int wlans_len = 1;

int setup_wifi(int try_time)
{
    wifi_scan();
    try_time--;
    const int wait_times = 20; // 10s x2 20s
    int tc = wait_times;
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
        tc--;
        if (try_time <= 0)
        {
            xouts("max try time exceed");
            return -1;
        }
        if (tc <= 0)
        {
            tc = wait_times;
            xouts("[timeout]");
            wifi_scan();
            try_time--;
        }
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    return 0;
}

void wifi_scan(bool connect)
{
    int n = WiFi.scanNetworks();
    int i;
    out_("[scanning]:");
    for (i = 0; i < n; i++)
    {
        out_(i);
        out_(":");
        String ss = WiFi.SSID(i);
        int j;
        for (j = 0; j < wlans_len; j++)
        {
            if (ss.startsWith(wlans[j][0]))
            {
                ssid = ss;
                password = wlans[j][1];
                break;
            }
        }
        outs(ss);
    }
    if (!connect)
        return;
    WiFi.begin(ssid, password);
    out_("[connect to]:");
    out_(ssid);
}

int wifi_connect(const char *ssid_, const char *password_, int timeout)
{
    ssid = ssid_;
    password = password_;
    WiFi.begin(ssid, password);
    int i = 0;
    timeout *= 10;
    for (i = 0; i < timeout; i++) // 15s
    {
        if (WiFi.status() == WL_CONNECT_FAILED)
        {
            return 0;
        }
        if (WiFi.status() != WL_CONNECTED)
        {
            delay(100);
            Serial.print(".");
        }
        else
        {
            Serial.println("");
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            return 1;
        }
    }
    return 0;
}

int cmd_wifi(int n, char *args[])
{
    if (n < 2)
    {
        if (!WiFi.isConnected())
        {
            xouts("WiFi not available");
            return 0;
        }
        var s = WiFi.SSID();
        outs(s);
        var rssi = WiFi.RSSI();
        outs(rssi);
        return 0;
    }
    if (n < 3)
    {
        if (Arg(1) == "-l")
        {
            for (int i = 0; i < wlans_len; i++)
            {
                out_(wlans[i][0]);
                out_(":");
                outs(wlans[i][1]);
            }
            return 0;
        }
        if (Arg(1) == "-d")
        {
            WiFi.disconnect();
            xouts("disconnected");
            return 0;
        }
        if (Arg(1) == "-do")
        {
            WiFi.disconnect(true);
            xouts("disconnected");
            return 0;
        }
        if (Arg(1) == "-s")
        {
            wifi_scan(false);
            return 0;
        }
        if (Arg(1) == "-sc")
        {
            wifi_scan(true);
            return 0;
        }
        outs("wifi :see wifi info");
        outs("wifi ssid psw:connect to wifi");
        outs("wifi -d[o]:disconnect wifi [turn off wifi]");
        outs("wifi -s[c]:scan APs [connect known AP after scanning]");
        outs("wifi -l:list all known ssid");
        outs("wifi -a ssid psw:add known wifi");
        outs("wifi -r ssid:remove ssid from known wifi list");
        return 0;
    }

    if (Arg(1) == "-a")
    {
        assert_msg(wlans_len < __known_ssids_list_len, "list overflow, please remove some ssid first, use: wifi -r ssid");
        assert_msg(n > 3, "bad args,useage: -a ssid psw");
        // append known ssid
        wlans[wlans_len][0] = args[2];
        wlans[wlans_len++][1] = args[3];
        return 0;
    }
    if (Arg(1) == "-r")
    {
        assert_msg(n > 2, "bad args,useage: -r ssid");
        int index = -1;
        for (int i = 0; i < wlans_len; i++)
        {
            if (wlans[i][0] == args[2])
            {
                index = i;
                break;
            }
        }
        assert_msg(index >= 0, "ssid not found");
        if (wlans_len == 1)
        {
            wlans_len = 0;
            return 0;
        }
        // swipe
        wlans[index][0] = wlans[wlans_len][0];
        wlans[index][1] = wlans[wlans_len--][1];
        return 0;
    }

    var ok = stop_schedule();
    int is_wifi_connected = wifi_connect(args[1], args[2]);
    if (ok)
        resume_schedule();
    if (!is_wifi_connected)
    {
        outs("wifi not available\n");
    }
    return 0;
}
